<?php

namespace App\Model;

use EasySwoole\DDL\Enum\Character;
use EasySwoole\DDL\Enum\Engine;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\ORM\Utility\Schema\Table;
use Throwable;

class AssetsModel extends AbstractModel
{
    protected $tableName = 't_assets';
    protected $autoTimeStamp = true; // 自动写入create_time和update_time 这两个字段是int

    /**
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function getAdjacent($where)
    {
        $where['is_deleted'] = 0;
        return $this->order('id', 'desc')->get($where);
    }

    /**
     * @throws Throwable
     * @throws Exception
     */
    public function addAdjacent($where)
    {
        $this->data($where, false);
        return $this->save();
    }

    public function schemaInfo(bool $isCache = true): Table
    {
        $table = new Table($this->tableName);

        $table->setIfNotExists();
        $table->setTableEngine(Engine::INNODB);
        $table->setTableCharset(Character::UTF8MB4_GENERAL_CI);
        $table->setTableComment('固定资产表');

        $table->colInt('id')->setIsAutoIncrement()->setIsPrimaryKey(true)->setColumnComment("ID");
        $table->colInt('sid', 64)->setDefaultValue(0)->setIsNotNull()->setColumnComment('商户id');
        $table->colVarChar('nid', 64)->setDefaultValue('')->setIsNotNull()->setColumnComment('分类id');
        $table->colVarChar('name', 128)->setDefaultValue('')->setColumnComment('资产名称');
        $table->colVarChar('image', 128)->setDefaultValue('')->setColumnComment('资产图片');
        $table->colDecimal('price', 10,2)->setDefaultValue(0.00)->setColumnComment('总价');
        $table->colDecimal('unit', 10,2)->setDefaultValue(0.00)->setColumnComment('单价');
        $table->colVarChar('label', 128)->setDefaultValue('')->setColumnComment('简介');
        $table->colInt('stock', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('库存');
        $table->colTinyInt('is_deleted', 1)->setDefaultValue(0)->setIsNotNull()->setColumnComment('是否删除：0.未删除，1.已删除');
        $table->colInt('create_time', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('创建时间戳');
        $table->colInt('update_time', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('更新时间戳');

        $table->indexNormal('nid_index', 'nid');
        $table->indexNormal('name_index', 'name');
        $table->indexNormal('price_index', 'price');
        $table->indexNormal('unit_index', 'unit');
        $table->indexNormal('stock_index', 'stock');

        return $table;
    }
}